import 'package:convergence_media/features/api/apis/circle_csavs_api.dart';
import 'package:convergence_media/features/app/repository/app_config_repository.dart';
import 'package:convergence_media/features/config/constants/api_config.dart';
import 'package:convergence_media/features/user/repositories/token_repository.dart';
import 'package:dio/dio.dart';

class CircleUnauthInterCeptor extends Interceptor {
  const CircleUnauthInterCeptor({
    required AppConfigRepository appConfigRepository,
    required TokenRepository tokenRepository,
  })  : _appConfigRepository = appConfigRepository,
        _tokenRepository = tokenRepository;

  final TokenRepository _tokenRepository;
  final AppConfigRepository _appConfigRepository;

  @override
  Future<void> onResponse(
    Response response,
    ResponseInterceptorHandler handler,
  ) async {
    // 圈子 500 没有 token
    if (response.statusCode != 500) {
      handler.next(response);
    }

    final currentHashId = _appConfigRepository.getCurrentHashId();
    final mainToken = await _tokenRepository.getMainToken(currentHashId!);

    // 刷新 token
    final dio = Dio(BaseOptions(baseUrl: ApiConfig.circleUrl));
    final circleCsavsApi = CircleCsavsApi(dio: dio);
    final loginTokenLoginResponse =
        await circleCsavsApi.postLoginTokenLogin(mainToken!);

    // 重试
    dio.options.headers
        .addAll({'token': loginTokenLoginResponse.data.loginToken});
    // Dio(response.requestOptions);

    handler.resolve(response);
    super.onResponse(response, handler);
  }
}
